package com.ray.service;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.formula.EvaluationSheet;
import org.apache.poi.ss.formula.ptg.RefErrorPtg;
import org.apache.xmlbeans.impl.xb.xsdschema.impl.PublicImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.backoff.FixedBackOff;

import com.fasterxml.jackson.annotation.JsonTypeInfo.Id;
import com.google.appengine.api.search.query.QueryParser.restriction_return;
import com.mchange.util.AssertException;
import com.ray.bean.AccountStatementBean;
import com.ray.bean.AdvancePaymentBean;
import com.ray.bean.BankBean;
import com.ray.bean.CompanyBean;
import com.ray.bean.DatatablesViewPageBean;
import com.ray.bean.PutOutOrderBean;
import com.ray.bean.ReceiptPaymentRecordBean;
import com.ray.bean.ReceiptPaymentRecordBean.ReceivePaymentDetailRecord;
import com.ray.bean.WarehouseInOutDetailBean;
import com.ray.exception.ServiceException;
import com.ray.bean.WarehouseInSumMoneyBean;
import com.ray.mapper.DingTalkMapper;
import com.ray.mapper.FinanceMapper;
import com.ray.mapper.WarehouseInSumMoneyMapper;
import com.ray.util.CreateIdUtil;
import com.ray.util.ExcelExportUtil;
import com.ray.util.RequestUtil;
import com.ray.util.ResponseUtil;
import com.ray.util.ReturnStringUtil;
import com.ray.util.StringUtil;
import com.sun.mail.mbox.Mailbox;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Service
public class FinanceService {
	
	
	@Autowired
	PutOutServiceNew putOutServiceNew ;
	@Autowired
	FinanceMapper financeMapper;
	@Autowired
	WarehouseInSumMoneyMapper warehouseInSumMoneyMapper;
	@Autowired
	DingTalkMapper dingTalkMapper;
	@Autowired
	CompanyService companyService;
	@Autowired
	ApprovalService approvalService;
	@Autowired
	WarehouseService warehouseService;
	 
	/**
	 * @isUrl true
	 * bankCardNumber 银行卡号
	 * bank 所属银行
	 * balance 余额
	 * @param map
	 * @return
	 */
    public  String  addBank (Map map) {
    	StringUtil.checkIsTrue(map, "bankCardNumber", "未获取到银行卡号");
    	StringUtil.checkIsTrue(map, "bank", "未获取到所属银行");
    	StringUtil.checkIsTrue(map, "balance", "未获取到余额");
    	Assert.isTrue(this.checkIsRepeat(map.get("bankCardNumber").toString(),map.get("loginCompany").toString()),"该银行卡号已存在");
    	int  row = financeMapper.addBank(map);
    	Assert.isTrue(row>0,ReturnStringUtil.ADD_ERROR);
    	return ReturnStringUtil.ADD_SUCCESS;
    }

     /**
      * 校验银行卡号是否重复
     * @param company 
     * @param string 
      * @return
      */
	private boolean checkIsRepeat(String bankCardNumber, String company) {
		Map map = new HashMap();
		map.put("bankCardNumber", bankCardNumber);
		map.put("loginCompany", company);
		List<BankBean> list = financeMapper.getAllBank(map);
		if(list.size()>0) {
			return false;
		}
		return true;
	}
	
	
	/**
	 * @isUrl true 
	 * 修改银行卡信息
	 * 仅可修改状态
	 * bankCardNumber 银行卡号
	 * status  状态 1 使用 2 禁用 
	 */
	public String updateBank(Map map ) {
		StringUtil.checkIsTrue(map, "bankCardNumber", "未获取到银行卡号");
		StringUtil.checkIsTrue(map, "status", "未获取到状态");
	    int status = Integer.parseInt(map.get("status").toString());
		//如果禁用
		if(status == 2) {
			map.put("relationBank", map.get("bankCardNumber"));
			List<ReceiptPaymentRecordBean> list = this.getReceiptPaymentRecord(map);
			List<ReceiptPaymentRecordBean> noeRve = list.stream().filter(dd->dd.getIsVerification()==0).collect(Collectors.toList());
			Assert.isTrue(noeRve.size()<=0,"该银行卡有未核销记录，不可核销");
		}
		//留空
		int  row = financeMapper.updateBank(map);
		Assert.isTrue(row>0,ReturnStringUtil.UPDATE_ERROR);
		return ReturnStringUtil.UPDATE_SUCCESS;
	}
	
	
	/**
	 * @isUrl true
	 * 获取所有银行卡信息
	 * status 
	 * bankCardNumber 银行卡号  模糊
	 * bank 银行
	 */
	public List<BankBean> getAllBank(Map map ){
		return  financeMapper.getAllBank(map);
	}

	
	/**
	 * 原方法改写
	 * 保存收付款记录
	 * jsonObject
	 * @param map
	 * @return
	 */
	public String saveReceiptPaymentRecord(Map<String, Object> map) {
		StringUtil.checkIsTrue(map, "jsonObject", "未获取到参数");
		String jsonStr = map.get("jsonObject").toString();
		JSONObject jsonObject = JSONObject.fromObject(jsonStr);
		Map classMap = new HashMap<>();
		classMap.put("detailList", ReceivePaymentDetailRecord.class);
		ReceiptPaymentRecordBean re = (ReceiptPaymentRecordBean) JSONObject.toBean(jsonObject, ReceiptPaymentRecordBean.class, classMap);
		List<ReceivePaymentDetailRecord> list = re.getDetailList();
		//如果是其他收付款单
		if(re.getSource() == 3) {
			
		}else if(re.getSource() == 1 ) {//如果是外协
			Map putOutMap=new HashMap();
			List<String> typeIdList = list.stream().map(ReceivePaymentDetailRecord::getInOutId).collect(Collectors.toList());
			putOutMap.put("loginCompany", map.get("loginCompany"));
			putOutMap.put("typeIdList", typeIdList);
			List<PutOutOrderBean> putOutList=putOutServiceNew.getPutoutOrderNoPage(putOutMap);
			for(ReceivePaymentDetailRecord receivePaymentDetailRecord : list) {
				receivePaymentDetailRecord.setId(StringUtil.getUUID());
				List<PutOutOrderBean> oneList  = putOutList.stream().filter(pp->receivePaymentDetailRecord.getInOutId().equals(pp.getTypeId())).collect(Collectors.toList());
                Assert.isTrue(oneList.size()>0,"外协记录不存在");	
                Assert.isTrue(1!=oneList.get(0).getIsBalance(),"该记录已结算完成，不可操作");
			}
		}else {//如果不是外协
			for(ReceivePaymentDetailRecord receivePaymentDetailRecord : list) {
				receivePaymentDetailRecord.setId(StringUtil.getUUID());
				Map inOutMap=new HashMap<>();
				inOutMap.put("id", receivePaymentDetailRecord.getInOutId());
				WarehouseInSumMoneyBean inOutRecord=warehouseInSumMoneyMapper.getInOutRecordById(inOutMap);
				Assert.isTrue(null!=inOutRecord,"该出入库记录不存在");
				Assert.isTrue(!"1".equals(inOutRecord.getIsBalance()),"该记录已结算，不可操作");
			}
		}
		re.setDetailList(list);
		SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		String dateStr=simpleDateFormat.format(new Date());
		map.put("createUser", map.get("loginUserId"));
		map.put("createTime", dateStr);
		map.put("data", re);
		//生成主id
		if(1==re.getType()) {
			map.put("id", dingTalkMapper.getApprovalNo(CreateIdUtil.RECEIPT));
		}else {//付款
			map.put("id", dingTalkMapper.getApprovalNo(CreateIdUtil.PAYMENT));
		}
		//只做保存不做审核
		map.put("status", 0);
		int row=warehouseInSumMoneyMapper.saveReceiptPaymentRecord(map);
		Assert.isTrue(row>0,ReturnStringUtil.OPERATION_ERROR);
		//审核过账
		if(re.getPayType() == 2) {
			Map<String,Object> approvalMap = new HashMap<String,Object>();
			approvalMap.put("loginCompany", map.get("loginCompany"));
			approvalMap.put("status", 1);
			approvalMap.put("loginUserId", map.get("loginUserId"));
			approvalMap.put("receivePaymentId", map.get("id"));
			this.approvalReceiptPaymentRecord(approvalMap);
		}
        return ReturnStringUtil.OPERATION_SUCCESS;
	}
	
	public List<ReceiptPaymentRecordBean> getReceiptPaymentRecord(Map map){
		return  financeMapper.getReceivePaymentRecord(map);
	}
	
	/**
	 * 审核
	 * receivePaymentId
	 * status
	 * @param map
	 */
	public String  approvalReceiptPaymentRecord(Map<String, Object> map) {
		StringUtil.checkIsTrue(map, "receivePaymentId", "未获取到id");
		StringUtil.checkIsTrue(map, "status", "未获取到状态");
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String time = simpleDateFormat.format(new Date());
		CompanyBean companyBean = companyService.getCompany(map);
		int status=Integer.parseInt(map.get("status").toString());
		map.remove("status");
		List<ReceiptPaymentRecordBean> list= financeMapper.getReceiptPaymentRecordHaveDetail(map);
		Assert.isTrue(list !=null && list.size()>0,"该记录不存在");
		ReceiptPaymentRecordBean receiptPaymentRecordBean=list.get(0);
		Assert.isTrue(receiptPaymentRecordBean.getStatus()==0,"该记录已审核，不可操作");
		
		if(1==status) {
			if(receiptPaymentRecordBean.getSource() != 3) {
				List<ReceivePaymentDetailRecord> detailRecords = receiptPaymentRecordBean.getDetailList();
				for(ReceivePaymentDetailRecord rr:detailRecords) {
					//如果是减少单
					if(rr.getAddReduceType() == 2) {
						rr.setAddReducePrice(rr.getAddReducePrice() * -1.0);
					}
				}
				Set<String> inOutIdSet = detailRecords.stream().map(ReceivePaymentDetailRecord::getInOutId).collect(Collectors.toSet());
			    Assert.isTrue(inOutIdSet.size()>0,"未获取到关联记录");
				//通过出入库id获取出入库信息
				List<WarehouseInSumMoneyBean> inOutList =  null;
				if(receiptPaymentRecordBean.getSource()==1) {
					inOutList = financeMapper.getPutOutListByInOutId(inOutIdSet);
				}else {
					inOutList = financeMapper.getInOutListBtInOutId(inOutIdSet);
				}
				List<WarehouseInSumMoneyBean> balanceList = inOutList.stream().filter(pp->"1".equals(pp.getIsBalance())).collect(Collectors.toList());
				Assert.isTrue(balanceList.size()<=0,"改出入库记录已被结算，不可审核通过");
				for(WarehouseInSumMoneyBean rr:inOutList) {
					List<ReceivePaymentDetailRecord> oneList = detailRecords.stream().filter(pp->pp.getInOutId().equals(rr.getId())).collect(Collectors.toList());
					//本次交接
					ReceivePaymentDetailRecord ff = oneList.get(0);
					BigDecimal beforeReceivePaymemntPrice = new BigDecimal(rr.getReceiptPaymentPrice());
					BigDecimal beforeAddReduceprice = new BigDecimal(rr.getAddReducePrice());
					BigDecimal thisPrice = new BigDecimal(ff.getPrice());
					BigDecimal thisAddReducePrice = new BigDecimal(ff.getAddReducePrice());
					beforeReceivePaymemntPrice = beforeReceivePaymemntPrice.add(thisPrice);
					beforeAddReduceprice = beforeAddReduceprice.add(thisAddReducePrice);
					rr.setReceiptPaymentPrice(beforeReceivePaymemntPrice.doubleValue());
					rr.setAddReducePrice(beforeAddReduceprice.doubleValue());
					if(companyBean.getIsAutoBalance() == 0) {  //如果是自动结算
						//如果付款已完成,结算掉
						if(rr.getInOutMoney()<=(beforeReceivePaymemntPrice.add(beforeAddReduceprice).doubleValue())) {
							rr.setIsBalance("1");
							rr.setBalanceTime(time);
						}
					}
				}
				int updateRow = 0 ;
				//如果是外协
				if(receiptPaymentRecordBean.getSource()==1) {
					updateRow=financeMapper.updatePutOutReceiptPaymentPrice(inOutList);
				}else {
					//更新出入库已收付金额
					updateRow=financeMapper.updateReceiptPaymentPrice(inOutList);
				}
				Assert.isTrue(updateRow>0,ReturnStringUtil.UPDATE_ERROR);
			}
			if(!"".equals(receiptPaymentRecordBean.getAdvancePaymenteceiveId())) {
				int aRow = financeMapper.advancePaymentReceiveIsUsed(receiptPaymentRecordBean.getAdvancePaymenteceiveId());
			}
		}
		map.put("status", status);
		int row=financeMapper.approvalReceiptPaymentRecord(map);
		Assert.isTrue(row>0,ReturnStringUtil.OPERATION_ERROR);
		return ReturnStringUtil.APPROVAL_SUCCESS;
	}
	
	
	
	/**
	 * 获取收付款总记录
	 * @param map
	 * @return
	 */
	public Map getReceivePaymentRecord(Map map){
		Map returnMap = new HashMap();
		DatatablesViewPageBean<ReceiptPaymentRecordBean> datatablesViewPageBean = new DatatablesViewPageBean<ReceiptPaymentRecordBean>();
	    List<ReceiptPaymentRecordBean> list = this.getReceiptPaymentRecord(map);
	    int count =  financeMapper.getReceivePaymentRecordCount(map);
	    //判断是否可审核此记录
	    Map approvalMap=new HashMap();
        approvalMap.put("type", "11");
        approvalMap.put("loginUserId", map.get("loginUserId"));
        approvalMap.put("loginCompany", map.get("loginCompany"));
		List<String> canApprovalUserId=approvalService.getApprovalIdByLoginId(approvalMap);
		for(ReceiptPaymentRecordBean rr:list) {
			if(canApprovalUserId.contains(rr.getCreateUser())) {
				rr.setIsCanApproval(1);
			}else {
				rr.setIsCanApproval(2);
			}
		}
        datatablesViewPageBean.setReturnData(list);
        datatablesViewPageBean.setiTotalDisplayRecords(count);
        datatablesViewPageBean.setiTotalRecords(count);
        returnMap.put("pageData", datatablesViewPageBean);
        if(null!=map.get("isSum") && !"".equals(map.get("isSum"))) {
			/**
			 * 求和  值为map appReceiptSum(已审收款总额)  notAppReceiptSum(待审收款总额) 
			 *            appPaymentSum(已审付款总额) notAppPaymentSum(待审付款总额)
			 */
			returnMap.put("sumData", financeMapper.getReceiptPaymentRecordSum(map));
		}
		return returnMap;
	}
	
	/**
	 * 获取出入库id收付款信息
	 * @param map
	 * @return
	 */
	public List<ReceiptPaymentRecordBean> getReceiptPaymentRecordByInOutId(Map map) {
		StringUtil.checkIsTrue(map, "inOutId", "未获取到出入库id");
		return financeMapper.getReceiptPaymentRecordByInOutId(map.get("inOutId").toString());
	}
	
	
	/**
	 * 通过收付款id获取收付款明细
	 * receivePaymentId 收付款id 
	 * source  来源
	 * @param map
	 * @return
	 */
	public List<ReceiptPaymentRecordBean> getReceiptPaymentRecordByMainId(Map map){
		StringUtil.checkIsTrue(map, "receivePaymentId", "未获取到收付款id");
		StringUtil.checkIsTrue(map, "source", "未获取到来源");
		//先确定是仓库产生的收付款记录还是外协产生的收付款记录
		int  source = Integer.parseInt(map.get("source").toString());
		List<ReceiptPaymentRecordBean> retuernList = null;
		//如果是外协
		if(3==source) {
			Assert.isTrue(false,"无明细记录");
		}else if(1==source) {
	    	retuernList = financeMapper.getPutOutReceiptPaymentRecordByMainId(map);
	    }else {
	    	retuernList = financeMapper.getReceiptPaymentRecordByMainId(map);
	    }
		return retuernList ;
	}
	
	/**
	 * @isUrl true
	 * idArray 收付款id集合
	 * @param map
	 * @return
	 */
	public String verificationReceiptPaymentRecord(Map map) {
		StringUtil.checkIsTrue(map, "idArray", "未获取到收付款id");
		String idArray = map.get("idArray").toString();
		JSONArray jsonArray = JSONArray.fromObject(idArray);
		List<String> idList = jsonArray.subList(0, jsonArray.size());
		Assert.isTrue(idList.size()>0,"未获取到收付款id"); 
		map.put("idList", idList);
		//对应的收付款记录
		List<ReceiptPaymentRecordBean> list = this.getReceiptPaymentRecord(map);
		Assert.isTrue(list.size()==idList.size(),"记录不存在");
		//未审核记录
		List<ReceiptPaymentRecordBean> notApprovalList = list.stream().filter(ff->ff.getStatus()!=1).collect(Collectors.toList());
		Assert.isTrue(notApprovalList.size()<=0,"未审核记录不可核销");
		List<ReceiptPaymentRecordBean> aleradyVerList = list.stream().filter(ff->ff.getIsVerification()!=0).collect(Collectors.toList());
		Assert.isTrue(notApprovalList.size()<=0,"已核销记录不可再次核销");
		List<ReceiptPaymentRecordBean>  noHaveBankList = list.stream().filter(ff->"".equals(ff.getRelationBank())).collect(Collectors.toList());
		Assert.isTrue(noHaveBankList.size()<=0,"无银行卡记录不可核销");
		//公司所有银行卡
		List<String> cardlist = list.stream().map(ReceiptPaymentRecordBean::getRelationBank).collect(Collectors.toList());
		map.put("cardList", cardlist);
		List<BankBean> bankList = this.getAllBank(map);
		//收款记录ReceiptPaymentRecordBean
		List<ReceiptPaymentRecordBean> receivablesList = list.stream().filter(ff->ff.getType()==1).collect(Collectors.toList());
		Map<String, List<ReceiptPaymentRecordBean>> receivablesMap = receivablesList.stream().collect(Collectors.groupingBy(ReceiptPaymentRecordBean::getRelationBank));
		for(String bankCard:receivablesMap.keySet()) {
			 //一张银行卡的收款记录
			 List<ReceiptPaymentRecordBean> oneCardReceive  = receivablesMap.get(bankCard);
			 BigDecimal receiveSumPrice = new BigDecimal(oneCardReceive.stream().mapToDouble(ReceiptPaymentRecordBean::getSumMoney).sum()) ;
			 boolean bool = false;
			 for(BankBean bankBean:bankList) {
				 //视同同一张银行卡
				 if(bankCard.equals(bankBean.getBankCardNumber())) {
					 bool = true;
					 Assert.isTrue(bankBean.getStatus() ==1 ,"银行卡:"+bankCard+"被禁用");
					 BigDecimal bankMoney = new BigDecimal(bankBean.getBalance());
					 bankBean.setBalance(bankMoney.add(receiveSumPrice).doubleValue());
					 break; 
				 }
			 }
			 Assert.isTrue(bool,"银行卡:"+bankCard+"不存在");
		}
		//付款记录
		List<ReceiptPaymentRecordBean> paymentList = list.stream().filter(ff->ff.getType()==2).collect(Collectors.toList());
		Map<String, List<ReceiptPaymentRecordBean>> paymentMap = paymentList.stream().collect(Collectors.groupingBy(ReceiptPaymentRecordBean::getRelationBank));
		for(String bankCard : paymentMap.keySet()) {
			List<ReceiptPaymentRecordBean> oneCardPayment = paymentMap.get(bankCard);
			BigDecimal paymentSumPrice = new BigDecimal(oneCardPayment.stream().mapToDouble(ReceiptPaymentRecordBean::getSumMoney).sum()) ;
			boolean bool= false;
			for(BankBean bankBean:bankList) {
				 //视同同一张银行卡
				 if(bankCard.equals(bankBean.getBankCardNumber())) {
					 bool= true;
					 Assert.isTrue(bankBean.getStatus() ==1 ,"银行卡:"+bankCard+"被禁用");
					 BigDecimal bankMoney = new BigDecimal(bankBean.getBalance());
					 bankBean.setBalance(bankMoney.subtract(paymentSumPrice).doubleValue());
					 Assert.isTrue(bankBean.getBalance()>=0,"银行卡:"+bankCard+"余额不足");
					 break; 
				 }
			 }
			Assert.isTrue(bool,"银行卡:"+bankCard+"不存在");
		}
		//修改银行卡余额
		int bankRow = financeMapper.updateBankCardBalance(bankList,map.get("loginCompany").toString());
		Assert.isTrue(bankRow>0,ReturnStringUtil.OPERATION_ERROR);
		int prRow = financeMapper.updatePaymentReceiveIsVerification(map);
		Assert.isTrue(prRow>0,ReturnStringUtil.OPERATION_ERROR);
		return ReturnStringUtil.OPERATION_SUCCESS;
	}
	
	
	
	public void exportReceivePaymentRecord(Map map) throws ServiceException, CloneNotSupportedException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, IOException{
		HttpServletRequest request=(HttpServletRequest) map.get("request");
		HttpServletResponse response= (HttpServletResponse) map.get("response");
		map.put("start", null);
		map.put("length", null);
		List<ReceiptPaymentRecordBean> list = this.getReceiptPaymentRecord(map);
		for(ReceiptPaymentRecordBean xx:list) {
			xx.setTypeStr();
			xx.setSourceStr();
			xx.setStatusStr();
		}
		String [] tableHeadFields={"收付款单号","类型","来源","金额","折算金额","收付方式","收付款方","银行卡号","所属银行","状态","制单人","制单时间","审核人","审核时间","是否核销","核销人","核销时间","备注"};
		String [] fields={"receivePaymentId","typeStr","sourceStr","sumMoney","conversionPrice","receiptPaymentMode","customerName","relationBank","bank","statusStr","createUserName","createTime","approvalUserName","approvalTime","verificationStr","verificationUser","verificationTime","reason"};
		String tempFolder=request.getServletContext().getRealPath("/")+"tempExcelFolder";
		File excelFile=ExcelExportUtil.createExcelFile(list,tempFolder,tableHeadFields,fields);
		ResponseUtil.downloadfile(response, excelFile, "收付款记录.xlsx", true);
	}
	
	
	/**
	 * 补充开票信息
	 * @param map
	 * @return
	 */
	public String supplementInvoicData(Map map) {
		StringUtil.checkIsTrue(map, "receivePaymentId", "未获取到收付款id");
		StringUtil.checkIsTrue(map, "invoicePrice", "未获取到开票金额");
		StringUtil.checkIsTrue(map, "invoiceDate", "未获取到开票日期");
		int row= financeMapper.supplementInvoicData(map);
		Assert.isTrue(row>0,ReturnStringUtil.OPERATION_ERROR);
		return ReturnStringUtil.OPERATION_SUCCESS;
	}
	
	/**
	 * 补充开票信息，含明细
	 * detailArray{
	 *   
	 * }
	 * @param map
	 * @return
	 */
	public String supplementInvoicIncludeDetail(Map map) {
		StringUtil.checkIsTrue(map, "receivePaymentId", "未获取到收付款id");
		StringUtil.checkIsTrue(map, "invoicePrice", "未获取到开票金额");
		StringUtil.checkIsTrue(map, "invoiceDate", "未获取到开票日期");
		StringUtil.checkIsTrue(map, "detailArray", "未获取到开票日期");
		String detailArray = map.get("detailArray").toString();
		JSONArray jsonArray = JSONArray.fromObject(detailArray);
		List<ReceivePaymentDetailRecord> list = (List<ReceivePaymentDetailRecord>) JSONArray.toCollection(jsonArray, ReceivePaymentDetailRecord.class);
		map.put("detail", list);
		int row= financeMapper.supplementInvoicData(map);
		Assert.isTrue(row>0,ReturnStringUtil.OPERATION_ERROR);
		return ReturnStringUtil.OPERATION_SUCCESS;
	}
	
	
	
	
	/**
	 * 添加预收付款记录
	 type;//预收付款类型 1 收款   2 付款
     source;//收付款用途 1合同定金  2担保金  3押金
     sourceStr;//收付款用途描述
     advanceNo;//合同编号
     paymentDay;//预收付款日期
     relationBank;//关联卡号
     sumMoney;//预收付金额
     receviePaymentUserName;//预收付款方
     isAduit 是审核过账则传 true  不传或false则不审核过账
	 * @param map
	 * @return
	 */
	public String advancePayAdd(Map map) {
		StringUtil.checkIsTrue(map, "type", "未获取到预收付款类型");
		StringUtil.checkIsTrue(map, "source", "未获取到预收付款用途");
		StringUtil.checkIsTrue(map, "sourceStr", "未获取到预收付款用途描述");
		StringUtil.checkIsTrue(map, "advanceNo", "未获取到合同编号");
		StringUtil.checkIsTrue(map, "relationBank", "未获取到关联卡号");
		StringUtil.checkIsTrue(map, "sumMoney", "未获取到预收付款金额");
		StringUtil.checkIsTrue(map, "paymentDay", "未获取到预收付款日期");
		StringUtil.checkIsTrue(map, "receviePaymentUserName", "未获取到收方");
		map.put("status", 0);
		map.put("isUsed", 0);
		int row= financeMapper.advancePayAdd(map);
		boolean isAduit=Boolean.parseBoolean(map.get("isAduit")==null?"fasle":map.get("isAduit").toString());
		if(isAduit) {
			Map<String,Object> aduitMap=warehouseService.setAduitMap(map);
			aduitMap.put("id", map.get("id"));
			aduitMap.put("status", 1);
			this.approvalAdvancePay(aduitMap);
		}
		Assert.isTrue(row>0,ReturnStringUtil.ADD_ERROR);
		return ReturnStringUtil.ADD_SUCCESS;
	}

	/**
	 * 批量审核预收付款记录
	 * idArray id集合
	 * status 状态
	 * @param map
	 * @return
	 */
	public String approvalAdvancePayBatch(Map map) {
		StringUtil.checkIsTrue(map, "idArray", "未获取到id");
		StringUtil.checkIsTrue(map, "status", "未获取到状态");
		String idArray = map.get("idArray").toString();
		JSONArray jsonArray = JSONArray.fromObject(idArray);
		List<String>  idList = jsonArray.subList(0, jsonArray.size());
		for(String id:idList) {
			map.put("id", id);
			this.approvalAdvancePay(map);
		}
		return ReturnStringUtil.APPROVAL_SUCCESS;
	}
	
	
	
	/**
	 * 审核预付款
	 * id 预收付款id
	 * status 状态
	 * @param map
	 * @return
	 */
	public  String  approvalAdvancePay(Map map) {
		StringUtil.checkIsTrue(map, "id", "未获取到id");
		StringUtil.checkIsTrue(map, "status", "未获取到状态");
		int status=Integer.parseInt(map.get("status").toString());
		map.remove("status");
		List<AdvancePaymentBean> list= this.getAdvancePaymentList(map);
		Assert.isTrue(list !=null && list.size()>0,"该记录不存在");
		AdvancePaymentBean advancePaymentBean=list.get(0);
		Assert.isTrue(advancePaymentBean.getStatus()==0,ReturnStringUtil.APPROVAL_ALREADY_EXCEPTION);
		map.put("status", status);
		int row=financeMapper.approvalAdvancePay(map);
		Assert.isTrue(row>0,ReturnStringUtil.OPERATION_ERROR);
		return ReturnStringUtil.APPROVAL_SUCCESS;
	}
	 
	/**
	 * 获取预收付款记录
	 * @param map
	 * @return
	 */
	private List<AdvancePaymentBean> getAdvancePaymentList(Map map){
		return financeMapper.getAdvancePaymentList(map);
	}
	
	/**
	 * 获取收付款记录
	 * @param map
	 * @return
	 */
	public Map getAdvancePayRecord(Map map) {
		Map returnMap = new HashMap();
		DatatablesViewPageBean<AdvancePaymentBean> datatablesViewPageBean = new DatatablesViewPageBean<AdvancePaymentBean>();
	    List<AdvancePaymentBean> list =  this.getAdvancePaymentList(map);
	    int count =  financeMapper.getAdvancePaymentListCount(map);
	    //判断是否可审核此记录
	    Map approvalMap=new HashMap();
        approvalMap.put("type", "14");
        approvalMap.put("loginUserId", map.get("loginUserId"));
        approvalMap.put("loginCompany", map.get("loginCompany"));
		List<String> canApprovalUserId=approvalService.getApprovalIdByLoginId(approvalMap);
		for(AdvancePaymentBean rr:list) {
			if(canApprovalUserId.contains(rr.getCreateUserId())) {
				rr.setIsCanApproval(1);
			}else {
				rr.setIsCanApproval(2);
			}
		}
        datatablesViewPageBean.setReturnData(list);
        datatablesViewPageBean.setiTotalDisplayRecords(count);
        datatablesViewPageBean.setiTotalRecords(count);
        returnMap.put("pageData", datatablesViewPageBean);
        if(null!=map.get("isSum") && !"".equals(map.get("isSum"))) {
			/**
			 * 求和  值为map appReceiptSum(已审收款总额)  notAppReceiptSum(待审收款总额) 
			 *            appPaymentSum(已审付款总额) notAppPaymentSum(待审付款总额)
			 */
			returnMap.put("sumData", financeMapper.getAdvancePayRecordSum(map));
		}
		return returnMap;
	}
	
	/**
	 * 获取对账单信息
	 * @param map
	 * @return
	 */
	public  List<AccountStatementBean> getAccountStatement(Map map){
		return financeMapper.getAccountStatement(map);
	}
	
	
	
	/**
	 * 获取收付款记录
	 * startTime 开始时间
	 * endTime 结束时间
	 * type 类型  1 收款  2 付款
	 * receiptPaymentMode 收付款方式
	 * createUser 经手人
	 * start 分页参数
	 * length 分页参数
	 * isSum 是否求和  传任意值则求和，不传或未''则不求和(点击分页和刷新列表时不需求和)
	 * status 状态  0 未审核 1 已审核 2 已退回
	 * @author nate 
	 */
//	public Map<String,Object> getReceiptPaymentRecord(Map<String, Object> map) {
//		Map<String,Object> returnMap=new HashMap<String,Object>();
//		DatatablesViewPageBean<ReceiptPaymentRecordBean> datatablesViewPageBean=new DatatablesViewPageBean<ReceiptPaymentRecordBean>();
//        Map approvalMap=new HashMap();
//        approvalMap.put("type", "11");
//        approvalMap.put("loginUserId", map.get("loginUserId"));
//        approvalMap.put("loginCompany", map.get("loginCompany"));
//		List<String> canApprovalUserId=approvalService.getApprovalIdByLoginId(approvalMap);
//		List<ReceiptPaymentRecordBean> returnList=warehouseInSumMoneyMapper.getReceiptPaymentRecord(map);
//		for(ReceiptPaymentRecordBean rr:returnList) {
//			if(canApprovalUserId.contains(rr.getCreateUser())) {
//				rr.setIsCanApproval(1);
//			}else {
//				rr.setIsCanApproval(2);
//			}
//		}
//		int count =warehouseInSumMoneyMapper.getReceiptPaymentRecordCount(map);
//		datatablesViewPageBean.setReturnData(returnList);
//		datatablesViewPageBean.setiTotalDisplayRecords(count);
//		datatablesViewPageBean.setiTotalRecords(count);
//		returnMap.put("pageData", datatablesViewPageBean);//分页数据
//		
//		//如果需要查询总和
//		if(null!=map.get("isSum") && !"".equals(map.get("isSum"))) {
//			/**
//			 * 求和  值为map appReceiptSum(已审收款总额)  notAppReceiptSum(待审收款总额) 
//			 *            appPaymentSum(已审付款总额) notAppPaymentSum(待审付款总额)
//			 */
//			returnMap.put("sumData", warehouseInSumMoneyMapper.getReceiptPaymentRecordSum(map));
//		}
//		
//		return returnMap;
//	}
	
	
}
